import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:get/get.dart';

/// 统一API服务类 - 管理所有运势相关的API调用
/// Unified API Service - Manages all fortune-related API calls
class UnifiedApiService extends GetxService {
  // 基础URL配置 Base URL configuration
  static const String _baseUrl = 'http://localhost:3000/api';
  
  // HTTP客户端 HTTP client
  final http.Client _client = http.Client();
  
  /// 获取每日运势
  /// Get daily fortune
  /// @param date 日期字符串 YYYY-MM-DD
  /// @returns 每日运势数据
  Future<Map<String, dynamic>> getDailyFortune(String date) async {
    try {
      final url = Uri.parse('$_baseUrl/fortune/daily?date=$date');
      
      print('🌟 调用每日运势API: $url');
      
      final response = await _client.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ).timeout(const Duration(seconds: 10));
      
      print('📡 API响应状态码: ${response.statusCode}');
      print('📡 API响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else if (response.statusCode == 401) {
        throw Exception('认证失败，请检查登录状态');
      } else if (response.statusCode == 404) {
        throw Exception('请求的资源不存在');
      } else if (response.statusCode == 500) {
        throw Exception('服务器内部错误');
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取每日运势失败: $e');
      rethrow;
    }
  }
  
  /// 获取生肖运势
  /// Get zodiac fortune
  /// @param shengXiao 生肖名称
  /// @param date 日期字符串 YYYY-MM-DD
  /// @returns 生肖运势数据
  Future<Map<String, dynamic>> getZodiacFortune(String shengXiao, String date) async {
    try {
      final url = Uri.parse('$_baseUrl/fortune/zodiac?shengXiao=$shengXiao&date=$date');
      
      print('🐲 调用生肖运势API: $url');
      
      final response = await _client.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ).timeout(const Duration(seconds: 10));
      
      print('📡 生肖运势API响应: ${response.statusCode}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取生肖运势失败: $e');
      rethrow;
    }
  }
  
  /// 获取配对测算
  /// Get compatibility analysis
  /// @param user1 用户1信息
  /// @param user2 用户2信息
  /// @returns 配对测算结果
  Future<Map<String, dynamic>> getCompatibilityAnalysis(
    Map<String, dynamic> user1,
    Map<String, dynamic> user2,
  ) async {
    try {
      final url = Uri.parse('$_baseUrl/fortune/compatibility');
      
      print('💕 调用配对测算API: $url');
      
      final response = await _client.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: json.encode({
          'user1': user1,
          'user2': user2,
        }),
      ).timeout(const Duration(seconds: 15));
      
      print('📡 配对测算API响应: ${response.statusCode}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取配对测算失败: $e');
      rethrow;
    }
  }
  
  /// 获取起名建议
  /// Get naming suggestions
  /// @param userInfo 用户信息
  /// @param preferences 起名偏好
  /// @returns 起名建议列表
  Future<Map<String, dynamic>> getNamingSuggestions(
    Map<String, dynamic> userInfo,
    Map<String, dynamic> preferences,
  ) async {
    try {
      final url = Uri.parse('$_baseUrl/fortune/naming');
      
      print('📝 调用起名建议API: $url');
      
      final response = await _client.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: json.encode({
          'userInfo': userInfo,
          'preferences': preferences,
        }),
      ).timeout(const Duration(seconds: 15));
      
      print('📡 起名建议API响应: ${response.statusCode}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取起名建议失败: $e');
      rethrow;
    }
  }
  
  /// 获取万年历信息
  /// Get calendar information
  /// @param date 日期字符串 YYYY-MM-DD
  /// @returns 万年历信息
  Future<Map<String, dynamic>> getCalendarInfo(String date) async {
    try {
      final url = Uri.parse('$_baseUrl/calendar/info?date=$date');
      
      print('📅 调用万年历API: $url');
      
      final response = await _client.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ).timeout(const Duration(seconds: 10));
      
      print('📡 万年历API响应: ${response.statusCode}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取万年历信息失败: $e');
      rethrow;
    }
  }
  
  /// 获取黄道吉日
  /// Get auspicious days
  /// @param year 年份
  /// @param month 月份
  /// @returns 黄道吉日列表
  Future<Map<String, dynamic>> getAuspiciousDays(int year, int month) async {
    try {
      final url = Uri.parse('$_baseUrl/calendar/auspicious?year=$year&month=$month');
      
      print('🌟 调用黄道吉日API: $url');
      
      final response = await _client.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ).timeout(const Duration(seconds: 10));
      
      print('📡 黄道吉日API响应: ${response.statusCode}');
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['success'] == true) {
          return data['data'];
        } else {
          throw Exception('API返回错误: ${data['message']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 获取黄道吉日失败: $e');
      rethrow;
    }
  }
  
  /// 释放资源
  /// Dispose resources
  @override
  void onClose() {
    _client.close();
    super.onClose();
  }
}